
package com.scalar.chiptrack.operations.dataentry.actions;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.sql.Date;


import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.util.LabelValueBean;


import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.adaptor.FabSortLot;
import com.scalar.chiptrack.adaptor.SortLotBinData;
import com.scalar.chiptrack.adaptor.dao.FabSortAdaptorDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.dataentry.forms.SortDataEntryForm;
import com.scalar.chiptrack.operations.dataentry.dao.SortDataEntryDAO;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.process.dao.LotDAO;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.process.Lot;

/*
 * Modified by Prabhanjan on 02 December 2003
 */

public final class SortDataEntryAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/sortDataEntry.do" ;
    public SortDataEntryAction ()
    {
    }

    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response ) throws Exception
    {

        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        //added by varma 10 sep 2004
        if ( user == null )
		{
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
			return ( mapping.findForward ( "login" ) );
		}
        else
        {
            if ( user.isActionAllowed ( Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }
        ArrayList partNumberList = new ArrayList ();
        String actionForward			= "success";
        ProductDao productDao = new ProductDao ();
        LotDAO lotDao = new LotDAO ();

        SortDataEntryForm sortDataEntryForm = ( SortDataEntryForm ) form;

        String action = request.getParameter ( "action" );
        if ( action == null ){
            action = "";
        }
        request.setAttribute ( "action", action );
		//Bhaskar added this code block on 7 December 2003
		String confirm = request.getParameter ( "confirm" );
		if ( confirm == null )
		confirm = "";

        partNumberList = ProductDao.getPartNumber ( "SORT" );

        PartNumber partNumber = null;

        ArrayList partNumberSelectList = new ArrayList ();

        for ( int i = 0; i < partNumberList.size (); i++ )
        {
            partNumber = ( PartNumber ) partNumberList.get ( i );
            partNumberSelectList.add ( new org.apache.struts.util.LabelValueBean ( partNumber.getPartNumber (), partNumber.getProcessStepId () + "/" + partNumber.getPartNumber () ) );
        }

        request.setAttribute ( "partNumberSelectList", partNumberSelectList );

        if ( action.equals ( "" ) )
        {
            return ( mapping.findForward ( actionForward ) );
        }

        ArrayList sortLocationList = null;
        ArrayList vendorLocationList = new ArrayList ();
        VendorLocation vendorLocation = null;

        String locationId = sortDataEntryForm.getLocationId ();
        String processStepId = sortDataEntryForm.getProcessStepId ();

        String quantityIn = sortDataEntryForm.getWaferQuantity ();
        String quantityOut = sortDataEntryForm.getQuantityOut ();
        String dateIn = sortDataEntryForm.getTestDateIn ();
        String dateOut = sortDataEntryForm.getTestDateOut ();
        String dateCode = sortDataEntryForm.getDateCode ();
        String vendorLot = sortDataEntryForm.getVendorLot ();
        String comments = sortDataEntryForm.getComments ();

        String lotId = sortDataEntryForm.getLotId ();


        if ( action.equals ( "location" ) || action.equals ( "save" ) || action.equals ( "lotnumber" ) || action.equals ( "partnumber" ) )
        {
            StringTokenizer st1 = new StringTokenizer ( processStepId, "/" );
            String pId = st1.nextToken ();
            String pNumber = st1.nextToken ();
            String psType = st1.nextToken ();

            sortLocationList = VendorDAO.getSelectedLocations ( Integer.parseInt ( pId ) );
            for ( int i = 0; i < sortLocationList.size (); i++ )
            {
                vendorLocation = ( VendorLocation ) sortLocationList.get ( i );
                vendorLocation.setLocationID ( vendorLocation.getLocationID () );
                vendorLocation.setLocationName ( vendorLocation.getLocationName () );
                vendorLocationList.add ( new org.apache.struts.util.LabelValueBean ( vendorLocation.getLocationName (), vendorLocation.getLocationID () + "/" + vendorLocation.getLocationName () ) );
            }
            request.setAttribute ( "locationSelectList", vendorLocationList );
        }


        if ( action.equals ( "location" ) || action.equals ( "lotnumber" ) || action.equals ( "save" ) )
        {
            ArrayList list = getLotList ( processStepId, locationId );
            request.setAttribute ( "lotNumbers", list );
            if ( action.equals ( "location" ) )
            {
                sortDataEntryForm.setLotId("0");
            }
        }


        if ( action.equals ( "lotnumber" ) )
        {
            StringTokenizer st1 = new StringTokenizer ( processStepId, "/" );
            String pId = st1.nextToken ();
            String pNumber = st1.nextToken ();
            String psType = st1.nextToken ();

            ArrayList noOfBins = LotDAO.getTotalNoOfBins(pId);
            String goodBins = (String) noOfBins.get(0);
            String rejectedBins = (String) noOfBins.get(1);
            try{
              Integer.parseInt(goodBins);
            }catch(Exception ex){
                goodBins = "1";   /// -----------hard coded but read the comments immediately below
				/*Initially the above value was set to 14 as a hard coded value. From now on ..based on an assumption
				we are setting the default value to be 1 instead of 14. Bhaskar on 05 Feb 2004*/
            }
            try{
              Integer.parseInt(rejectedBins);
            }catch(Exception ex){
                rejectedBins = "1";    /// -----------hard coded but read the comments immediately below
				/*Initially the above value was set to 14 as a hard coded value. From now on ..based on an assumption
				we are setting the default value to be 1 instead of 14. Bhaskar on 05 Feb 2004*/
            }
            //System.out.println("ProcesStep_ID "+ pId + "goodBins"+goodBins + "rejectedBins"+rejectedBins);
            sortDataEntryForm.setGoodBinsCount( goodBins );
            sortDataEntryForm.setRejectedBinsCount( rejectedBins );
            int processStepIdInt = 0;
            try
            {
                processStepIdInt = Integer.parseInt ( pId.trim() );
            }
            catch( Exception e ) { }

            sortDataEntryForm.setFabGrossDie( LotDAO.getFabGrossDieFromProcessStepId( null, processStepIdInt ) );
            LotDetails lotDetails = new LotDetails();

            if ( ( !"-1".equals ( lotId ) ) )
            {

                StringTokenizer st = new StringTokenizer ( lotId, "$" );
                String strLotId = st.nextToken ();
                String strLotNo = st.nextToken ();
                String strLotStatus = st.nextToken ();
                String poNumber = "";

                Lot lot = LotDAO.getSortLotData ( strLotId );

                sortDataEntryForm.setWaferQuantity  ( lot.getQuantityIn () );
                sortDataEntryForm.setQuantityOut    ( lot.getQuantityOut () );
                sortDataEntryForm.setTestDateIn     ( lot.getDateIn () );
                sortDataEntryForm.setTestDateOut    ( lot.getDateOut () );
                sortDataEntryForm.setDateCode       ( lot.getDateCode () );
                sortDataEntryForm.setVendorLot      ( lot.getVendorLot () );
                sortDataEntryForm.setComments       ( lot.getComments () );
                sortDataEntryForm.setLotCategory    ( lot.getLotCategory() );
                sortDataEntryForm.setVendorLot      ( lot.getVendorLot() );
                // changed by hareesh on 21th Febraury 2004
                // -- START --
				// Added by ravikanth for Purchase Order ID
				/*if( lot.getPOrderID() != -1 && lot.getPOrderID() != 0 )
				{
					poNumber = LotDAO.getPoNumber ( lot.getPOrderID() );
				}
				sortDataEntryForm.setPoNumber    	( poNumber );*/
                if( lot.getPOrderID() != null && lot.getPOrderID().trim().length() != 0 )
				{
					sortDataEntryForm.setPoNumber( lot.getPOrderID() );
				}else{
                    sortDataEntryForm.setPoNumber( "" );
                }
				// -- END --
                // added by hareesh on 7th December 2003
                // -- START --
                // to updated bin sort lot data
				//Bhaskar added this code block on 2 Feb 2004.
				String yield = "";
				try
				{
					yield = lot.getYield();
					if ( ( ( yield != null ) && ( yield.trim().equalsIgnoreCase( "null" ) ) ) || ( yield == null ) || ( yield.trim().length() == 0 ) )
					{
						yield = "";
					}
					else
					{
						yield = StringUtils.formatAmount((float)(new Double(yield).doubleValue()), "###.##");
					}
				}
				catch (Exception e )
				{
					yield = "";
				}

				sortDataEntryForm.setYield( yield );
                sortDataEntryForm.setGrossDice( lot.getGrossDie() );
				if ( lot.getAvgGoodDie() != null && lot.getAvgGoodDie().trim().length() > 0 )
                {
                    sortDataEntryForm.setAvgGoodDie ( lot.getAvgGoodDie() );
                }
                else
                {
                    sortDataEntryForm.setAvgGoodDie ("");
                }
                
                String qtyOutAsString = sortDataEntryForm.getQuantityOut();
                if( qtyOutAsString != null )
                {
                    SortLotBinData sortLotBinData = LotDAO.getSortLotBinData( strLotId  );
                    if( sortLotBinData != null ){
                        request.setAttribute( "sortLotBinData" , sortLotBinData );
                    }
                }

                // -- END--
            }
            else
            {
				//Bhaskar added this small code snippet on 03 Mar 2004 inorder to get the
				//FL_Die_Size from fab_table
				String fabProcStepId = LotDAO.getFabProcessStepIdForSortProcessStepId ( null, pId );
                sortDataEntryForm.setGrossDice( ""+sortDataEntryForm.getFabGrossDie() );
                sortDataEntryForm.setLotNo          ( "" );
                sortDataEntryForm.setWaferQuantity  ( "" );
                sortDataEntryForm.setQuantityOut    ( "" );
                sortDataEntryForm.setTestDateIn     ( StringUtils.formatDateToString(new Date(System.currentTimeMillis()), "MM/dd/yyyy") );
                sortDataEntryForm.setTestDateOut    ( "" );
                sortDataEntryForm.setYield          ( "" );
                sortDataEntryForm.setDateCode       ( "" );
                sortDataEntryForm.setVendorLot      ( "" );
                sortDataEntryForm.setComments       ( "" );

                sortDataEntryForm.setPoNumber( "" );
            }

            request.setAttribute ( "lotnumber", "true" );
            request.setAttribute( "lotCategoryList", lotDetails.getLotCategoryType() );
        }


         if( "allLotInfo".equals( action ) )
        {
            String lotprocessstepId = request.getParameter("ProcessStepId");
            String lotlocationId = request.getParameter("LocationId");
            String lotNo         = request.getParameter("LotNo");

            StringTokenizer st = new StringTokenizer ( lotprocessstepId, "/" );
            String pId = st.nextToken ();
            st.nextToken ();

            st = new StringTokenizer ( lotlocationId, "/" );
            String locId = st.nextToken ();
            st.nextToken ();

            ArrayList allLotsList = null;
            try
            {
                 String newlotId = LotDAO.getLotId( lotNo , locId, pId  );

                if ( newlotId != null && newlotId.length() > 0 )
                {
                    allLotsList = LotDAO.getAllLotDetails( newlotId );
                }

                request.setAttribute("allLotsList", allLotsList );
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
            return mapping.findForward( "alllotInfo" );
        }

        if ( action.equals ( "save" ) )
        {
            if ( quantityIn.equals ( "" ) )
            {
                quantityIn = null;
            }
            if ( dateIn.equals ( "" ) )
            {
                 dateIn = null;
            }
            if ( quantityOut.trim().equals ( "" ) )
            {
                quantityOut = null;
            }
            if ( dateOut.equals ( "" ) )
            {
                dateOut = null;
            }
             if ( dateCode.trim().equals ( "" ) )
            {
                dateCode = null;
            }
            String lotCurrentStatus = "Running";

            /*if(quantityOut != null)
            {
                lotCurrentStatus = "Close";
            } */
            // changed by hareesh on 11/12/2003
            // Because for wafer Quantity out is calculated even data for one single wafer is entered.
            // so if date out entered we have close the lot.
            if(dateOut != null)
            {
                lotCurrentStatus = "Close";
            }

			//check for duplication or lot number repetition. Bhaskar on 6 December 2003
			StringTokenizer stok1 = new StringTokenizer (processStepId,"/");
			StringTokenizer stok2 = new StringTokenizer (locationId,"/");
			String procStepId = stok1.nextToken();
			String locatId = stok2.nextToken();
			String lot_ID = LotDAO.getLotIdInDataEntry ( null, procStepId, locatId, sortDataEntryForm.getLotNo() );
           	if(lot_ID == null) {
                lot_ID = "";   }
               lot_ID = lot_ID.trim();

			if ( lotId.equals ( "-1" ) && (!confirm.equals("confirm")))
			{
        		if ( "".equalsIgnoreCase(lot_ID)==false)
				{
                    // added by sahoo on 26th march 2004
                        String goodBins = sortDataEntryForm.getGoodBinsCount();
                       SortLotBinData sortLotBinData =  getBinDataFromRequest( sortDataEntryForm.getWaferQuantity (), request ,  goodBins );
                        if( sortLotBinData != null )
                        {
                          request.setAttribute( "sortLotBinData" , sortLotBinData );
                        }
                    // end of addition by sahoo
					request.setAttribute("showError", "TRUE");
					return mapping.findForward( actionForward );
				}
			}

			DBTransaction dbTransaction = null;
			boolean success = false;
			try
			{
				dbTransaction = DBTransaction.getInstance ();
				dbTransaction.begin ();
			}
			catch ( Exception e )
			{
				e.printStackTrace ();
			}


            // Step 1 : Save sort_lot table
            String strLotId = null;
            String strLotNo = null;
            String strLotStatus = null;
            if ( !lotId.equals ( "-1" ) )
            {
                StringTokenizer st = new StringTokenizer ( sortDataEntryForm.getLotId (), "$" );
                strLotId = st.nextToken ();
                strLotNo = st.nextToken ();
                strLotStatus = st.nextToken ();
            }
            else
            {
				strLotId = "-1";
                strLotNo = sortDataEntryForm.getLotNo ();
            }


            StringTokenizer st1 = new StringTokenizer ( processStepId, "/" );
            String pId = st1.nextToken ();
            String pNumber = st1.nextToken ();
            String psType = st1.nextToken ();


            st1 = new StringTokenizer ( sortDataEntryForm.getLocationId (), "/" );
            String locId = st1.nextToken ();
            String vendorName = st1.nextToken ();

            FabSortLot wipSummary = new FabSortLot ();

			// Ravi Kanth added this code for PONumber on 11 Feb 2004
			String poNumber = "";
			poNumber = sortDataEntryForm.getPoNumber();
            String category = "";
            category = sortDataEntryForm.getLotCategory();
            
            wipSummary.setCustProduct   ( pNumber );
            wipSummary.setDateIn        ( dateIn );
            wipSummary.setDateOut       ( dateOut );
            wipSummary.setQtyIn         ( quantityIn );
            wipSummary.setQtyOut        ( quantityOut );
            wipSummary.setLotStatus     ( lotCurrentStatus );
            wipSummary.setLotId         ( strLotNo );
            wipSummary.setVendorName    ( vendorName );
			wipSummary.setPoNumber		( poNumber );
            wipSummary.setDateCode		( dateCode );
            wipSummary.setVendorLot		( vendorLot );
            wipSummary.setComments		( comments );
            wipSummary.setLotCategory	( category );

            // added by hareesh on 11th Decemeber 2003
            String shipYield	= sortDataEntryForm.getYield();
            String grossDice	= sortDataEntryForm.getGrossDice();
			String avgGoodDie	= sortDataEntryForm.getAvgGoodDie();
            wipSummary.setGrossDie ( grossDice );
			//This if else condition is added by Bhaskar on 2 Feb 2004
			if (shipYield.trim().length() == 0 )
			{
				wipSummary.setShipYield ( null );
			}
			else
			{
	            wipSummary.setShipYield ( shipYield );
			}
			if ( avgGoodDie.trim ().length () == 0 )
			{
				wipSummary.setAvgGoodDie ( null );
			}
			else
			{
				wipSummary.setAvgGoodDie ( avgGoodDie );
			}
            ArrayList wipSummaryList = new ArrayList ();
            wipSummaryList.add ( wipSummary );


			/*This method is called by Bhaskar  and is added on 08 December  2003.
			 * To update the lot_current_status to close from running. This will be
			 * called in all DataEntry classes just before actual create or updation
			 * concept. Even if a lotId of -1 is passed still the procedure will execute
			 * successfully
			 */
            /*if( strLotId != null && !strLotId.equalsIgnoreCase( "-1" ) )
		    {
                LotDAO.changeLotStatusToCloseByLotId ( dbTransaction, strLotId );
            }*/

            if( confirm.equals("confirm") )
            {
                LotDAO.updateLotStatus(dbTransaction, Integer.parseInt( lot_ID ), confirm );
            }
            LotDAO.saveSortLot ( dbTransaction, wipSummaryList, user.getUserName (), psType );

			/*
			Bhaskar added this if condition on 21 Jan 2004 inorder to get the new Lot Id in case its created along
			with sort bin data. This lot id will be passed in the saveSortLotBinDataEntry method that is called
			below.
			*/

			if (strLotId.equals("-1"))
			{
        		strLotId = LotDAO.getLotId(dbTransaction, sortDataEntryForm.getLotNo().trim(), locId, pId); //get LotId in case of the new lot creation
			}

            // added by hareesh on 6th December 2003
            // -- START --
            // To save bin informaton into the database
               String goodBins = sortDataEntryForm.getGoodBinsCount();
               SortLotBinData sortLotBinData =  getBinDataFromRequest( wipSummary, request , shipYield, grossDice, goodBins );
               if( sortLotBinData != null ){
                    FabSortAdaptorDAO.saveSortLotBinDataEntry( dbTransaction, sortLotBinData, strLotId, pId );
                    request.setAttribute( "sortLotBinData" , sortLotBinData );
               }else {
                   //System.out.println("Sort Bin Data is not instered/updated");
               }
         //   Commented the saving in sort bin release table
           /* if( "Close".equalsIgnoreCase(lotCurrentStatus))
            {
                int processStepIdInt;
                int lotIdInt;
                int goodBinsCount = 1;

                try
                {
                    processStepIdInt = Integer.parseInt( pId );
                    lotIdInt = Integer.parseInt( strLotId );
                    goodBinsCount = Integer.parseInt( goodBins);
                }
                catch( NumberFormatException e)
                {
                    e.printStackTrace();
                    processStepIdInt = -1;
                    lotIdInt = -1;
                }
                SortDataEntryDAO.saveSortLotBinDataEntryInSortBinReleaseTable( dbTransaction, processStepIdInt, lotIdInt, goodBinsCount);
                //to close sort release if any issued..
                SortDataEntryDAO.closeSortReleases( dbTransaction, lotIdInt );
            }*/
            // -- END --

            success = true;
            try
            {
                if ( success == true )
                {
					if (dbTransaction != null)
					{
						dbTransaction.commit ();
					}
                }
                else
                {
                    dbTransaction.rollback ();
                }
            }
            catch ( Exception e1 )
            {
                e1.printStackTrace ();
            }

            ArrayList list = getLotList ( processStepId, locationId );

            if ( lotId.equals ( "-1" ) )
            {
                for ( int i = 0; i < list.size (); i++ )
                {
                    LabelValueBean valueBean = ( LabelValueBean ) list.get ( i );
                    String label = valueBean.getLabel ();
                    if ( label.equals ( strLotNo ) )
                    {
                        sortDataEntryForm.setLotId ( valueBean.getValue () );
                    }
                }
            }
            request.setAttribute ( "lotNumbers", list );
            HashMap info = new LinkedHashMap ();
            info.put ( "Data has been updated successfully", "" );
            request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
            actionForward = "saveSuccess";
        }
        request.removeAttribute ( "sortdataentryform" );
        request.setAttribute ( "sortdataentryform", sortDataEntryForm );

        if( action.equalsIgnoreCase( "null" ) || action.equalsIgnoreCase( "" ) )
        {
            sortDataEntryForm.setProcessStepId( "0" );
        }

        return ( mapping.findForward ( actionForward) );
    }

    private ArrayList getLotList ( String processStepId, String locationId )
    {
        java.util.ArrayList list = new ArrayList ();
        try
        {
            StringTokenizer st = new StringTokenizer ( processStepId, "/" );
            String pId = st.nextToken ();
            String pNumber = st.nextToken ();
            String psTypeName = st.nextToken ();

            st = new StringTokenizer ( locationId, "/" );
            String locId = st.nextToken ();

            String locName = st.nextToken ();

            ArrayList lotNumberList = LotDAO.getRunningLotNumbersByPSTypeName ( pId, locId, "SORT" );
            Lot lot = null;
            list = new java.util.ArrayList ();

            for ( int i = 0; i < lotNumberList.size (); i++ )
            {
                lot = ( Lot ) lotNumberList.get ( i );
                list.add ( new org.apache.struts.util.LabelValueBean ( lot.getLotNumber (), lot.getLotId () + "$" + lot.getLotNumber () + "$" + lot.getStatus () ) );
            }
        }
        catch ( Exception e )
        {
        }
        return list;
    }
    // added by sahoo on 26th march 2004
    public SortLotBinData getBinDataFromRequest( String sortLot, HttpServletRequest request, String goodBinsCount )
    {

        SortLotBinData sortLotBinData = null;
        int waferSize = 0;
        try{
               waferSize =  Integer.parseInt(sortLot);
           }
        catch (Exception ex)
        {
            waferSize = 0;
        }
        int goodBins = 0;
        try
        {
            goodBins =  Integer.parseInt(goodBinsCount);

        }
        catch (Exception ex)
        {
            goodBins = 0;
        }
        if (waferSize == 0)
        {
            return null;
        }
        try
        {

            String[] waferId  = request.getParameterValues("waferId");
            String[] binRejected  = request.getParameterValues("binRejected");

            String[] yield = request.getParameterValues("binYield");
            String[][] goodBinsValues = new String[goodBins+1][waferSize];
            for(int binCount = 0; binCount <= goodBins; binCount++ ){
            goodBinsValues[binCount] = request.getParameterValues("bin_"+binCount);
        }
        if(waferId == null)
        {
            for(int count = 0; count <= goodBins; count++ )
            {
                if( goodBinsValues[count] == null )
                {
                    return null;
                }
            }
        }

        for(int count = 0; count < waferSize; count++ )
        {
            if ( waferId[count] == null || waferId[count].trim().length() == 0 )
            {
               return null;
            }
            else
            {
                for(int binCount = 0; binCount <= goodBins; binCount++)
                {
                    String tempStr = goodBinsValues[binCount][count];
                    if ( (tempStr == null) || (tempStr.trim().length() == 0) )
                    {
                        goodBinsValues[binCount][count] = "0";
                    }
                }
            }
        }
        ArrayList waferList = new ArrayList(waferSize);
        ArrayList binList   = new ArrayList(waferSize);
        for(int count = 0; count < waferSize; count++ )
        {
            ArrayList temp_it = new ArrayList(5);
            temp_it.add ( 0, waferId[count] );
            temp_it.add ( 1, null ); // test time
            temp_it.add(2, ""+getGoodDiceFromGoodDiceCount( goodBins, goodBinsValues, count ) );
            temp_it.add ( 3, yield[count] ); // yeild
            temp_it.add ( 4, goodBinsValues[0][count] ); // bin1
            temp_it.add ( 5, binRejected[count]);//Rejected bin
            waferList.add ( count, temp_it );
            ArrayList temp_binList = new ArrayList(11);

        for(int binCount =0; binCount <= 14; binCount++  )
        {
            if( binCount <= goodBins )
            {
                temp_binList.add(binCount,goodBinsValues[binCount][count] );
            }
            else
            {
                temp_binList.add(binCount , 0+"");
            }
         }
            binList.add(count, temp_binList);
        }

        sortLotBinData = new SortLotBinData(
        null,  // vendorName
        null, // product
        null,       // LotId
        null,                     // program
        null,                     // tester
        null,                     // probecard
        null,                // grossDice
        null,       // shipSlice
        null,      // shipDice
        null,                // shipYield
        null,     // shipTime
        null,                     // reportTime
        waferList,                //waferIdList
        new ArrayList(),           //totalList // dumy
        new ArrayList(),           //averageList // dumy
        new ArrayList(),           //precentageList // dumy
        binList                    //binList
        );

          }catch(Exception ex){
            sortLotBinData = null;
            ex.printStackTrace();
          }

        return sortLotBinData;

    }
   // end of addition by sahoo on 26th march 2004


    // added by hareesh on 6th Devember 2003
    public SortLotBinData getBinDataFromRequest( FabSortLot sortLot , HttpServletRequest request, String shipYield, String grossDice, String goodBinsCount ){
        //System.out.println("Entered in getBinDataFromRequest() inside Action class");
        /*SortLotBinData(String vendorName, String product, String lotId, String program, String tester, String probeCard,
          String grossDice, String shipSlice, String shipDice,
		  String shipYield, String shipTime, String reportTime,
          ArrayList waferIdList, ArrayList totalList, ArrayList averageList,
		  ArrayList percentageList, ArrayList binList);*/
          SortLotBinData sortLotBinData = null;
          int waferSize = 0;
          try{
            waferSize =  Integer.parseInt(sortLot.getQtyIn());
              //System.out.println("Values of waferSize is.."+waferSize);
          } catch (Exception ex){
              waferSize = 0;
          }
          int goodBins = 0;
          try{
            goodBins =  Integer.parseInt(goodBinsCount);
              //System.out.println("Values of goodBins is.."+goodBins);
          } catch (Exception ex){
              goodBins = 0;
          }
          //System.out.println("waferQtyin : "+waferSize);
          //System.out.println("GoodBinsCount"+goodBins);

          if (waferSize == 0)
          {
            return null;
          }
          try{
              //System.out.println("Entered inside the try block*********");
          String[] waferId  = request.getParameterValues("waferId");
          String[] binRejected  = request.getParameterValues("binRejected");
              //System.out.println("size of waferId is..."+waferId.length);
          String[] yield = request.getParameterValues("binYield");
          String[][] goodBinsValues = new String[goodBins+1][waferSize];
         for(int binCount = 0; binCount <= goodBins; binCount++ ){
             goodBinsValues[binCount] = request.getParameterValues("bin_"+binCount);
         }

              // if no data present lastest for one wafer
              // then assumed there is no data for the wafer's in sort bins
          if(waferId == null)
          {
             for(int count = 0; count <= goodBins; count++ )
             {
                if( goodBinsValues[count] == null )
                {
                  return null;
                }
             }
          }

			for(int count = 0; count < waferSize; count++ )
			{
				if ( waferId[count] == null || waferId[count].trim().length() == 0 ){
                    //System.out.println("I am here as waferId is null");
					return null;
				}
				else
				{
					//system.out.println ( "count "+count+" : "+waferId[count]);
					for(int binCount = 0; binCount <= goodBins; binCount++)
					{
						String tempStr = goodBinsValues[binCount][count];
						if ( (tempStr == null) || (tempStr.trim().length() == 0) )
						{
							goodBinsValues[binCount][count] = "0";
						}
						//system.out.println("*"+goodBinsValues[binCount][count]+"#");
					}
				}
			}
          ArrayList waferList = new ArrayList(waferSize);
          ArrayList binList   = new ArrayList(waferSize);
          for(int count = 0; count < waferSize; count++ ){
                ArrayList temp_it = new ArrayList(5);
                temp_it.add ( 0, waferId[count] );
                temp_it.add ( 1, null ); // test time
				temp_it.add(2, ""+getGoodDiceFromGoodDiceCount( goodBins, goodBinsValues, count ) );//now placed as Good Die by Bhaskar on 04 Feb 2004
                //temp_it.add ( 2, goodBinsValues[0][count] ); // assumed good Deice = Bin1 old code commented on 04 Feb 2004 by Bhaskar
                temp_it.add ( 3, yield[count] ); // yeild
                temp_it.add ( 4, goodBinsValues[0][count] ); // bin1
                temp_it.add ( 5, binRejected[count]);//Rejected bin
                waferList.add ( count, temp_it );
                //System.out.println(temp_it);
                ArrayList temp_binList = new ArrayList(11);
                //temp_binList.add( 0 , waferQtyIn[count]+"" );
                for(int binCount =0; binCount <= 14; binCount++  ){  /// -----------hard coded
                    if( binCount <= goodBins ){
                          temp_binList.add(binCount,goodBinsValues[binCount][count] );
                          //System.out.println(binCount+" "+count+" "+goodBinsValues[binCount][count]);
                     } else {
                            temp_binList.add(binCount , 0+"");
                      }
                    //temp_binList.add( binCount+1 , "0"); // bin2 to bin11
                }
                binList.add(count, temp_binList);
                //System.out.println(temp_binList);
          }
              //System.out.println("Before creating sortLotBinData object.."+sortLotBinData);

          sortLotBinData = new SortLotBinData(
                                sortLot.getVendorName(),  // vendorName
                                sortLot.getCustProduct(), // product
                                sortLot.getLotId(),       // LotId
                                null,                     // program
                                null,                     // tester
                                null,                     // probecard
                                grossDice,                // grossDice
                                sortLot.getQtyIn(),       // shipSlice
                                sortLot.getQtyOut(),      // shipDice
                                shipYield,                // shipYield
                                sortLot.getDateOut(),     // shipTime
                                null,                     // reportTime
                                waferList,                //waferIdList
                                new ArrayList(),           //totalList // dumy
                                new ArrayList(),           //averageList // dumy
                                new ArrayList(),           //precentageList // dumy
                                binList                    //binList
                            );
              //System.out.println("After creating sortLotBinData Object is.."+sortLotBinData);
          }catch(Exception ex){
              System.out.println("Exceptin raised..."+ex.getMessage());
            sortLotBinData = null;
            ex.printStackTrace();
          }
        //System.out.println("B4 Returning sortLotBinData value is.."+sortLotBinData);
        return sortLotBinData;
    }


	/*
	This method is added by Bhaskar on 04 Feb 2004 inorder to calculate the good dice sum from the good bin count that is
	obtained from the "lotNumber" action block in the execute method. Initally there were some assumptions like adding
	only the first bin as good bins. But now its based on the count that we get from the Wip_Step_Bin_Table.
	*/
	private int getGoodDiceFromGoodDiceCount(int goodBinCount, String binDetails[][], int waferId)
	{
		int goodDice = 0;
		//for ( int temp = 0; temp < waferSize ; temp++ )
		//{
			for ( int binTemp = 0 ; binTemp < goodBinCount ; binTemp++ )
			{
				try
				{
					goodDice += Integer.parseInt(binDetails[binTemp][waferId].trim());
				}
				catch(Exception e)
				{
					goodDice += 0;//incase some junk value is passed
				}
			}
		//}
		return goodDice;
	}

}
